<template>
  <div v-to-drag :class="video">
    <span class="close-video" @click="stopVideo()">X</span>
    <video id="video" ref="video"></video>
    <canvas ref="canvas" class="no-display"></canvas>
  </div>
</template>
<script>
import { ToDragDirective } from '@howdyjs/to-drag';

import { getToken } from '@/utils/auth'

export default {

  name: 'examVideo',
  props: {
    value: String
  },
  directive: {
    'to-drag': ToDragDirective
  },
  data() {
    return {
      mediaStreamTrack: {},
      video_stream: '', // 视频stream
      video: "video",
      websocketUrl: process.env.VUE_APP_WS_API,
      socket: null,
      interval: null,
      examId: ''
    }
  },
  watch: {
    value: {
      handler() {
        this.examId = this.value
      }
    }
  },
  created() {
    this.examId = this.value
    this.getCamera();
    this.initWebSocket();
    window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
    window.addEventListener('unload', e => this.unloadHandler(e))
  },
  destroyed() {
    this.socket.close();
    window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
    window.removeEventListener('unload', e => this.unloadHandler(e))
  },

  methods: {

    getCamera() {
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }

      navigator.mediaDevices
        .getUserMedia({
          video: true,
          // audio: true,
        })
        .then((stream) => {
          this.mediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[0];

          this.video_stream = stream;
          this.$refs.video.srcObject = stream;
          this.$refs.video.play();

        })
        .catch(err => {
          //TODO 执行回调到设置页面，判断是是否成功开启摄像头
          console.log(err)
        })
    },
    stopVideo() {
      if (typeof this.video_stream.stop === 'function') {
        this.video_stream.stop();
      } else {
        let tracksList = [this.video_stream.getAudioTracks(), this.video_stream.getVideoTracks()];

        for (let i = 0; i < tracksList.length; i++) {
          let tracks = tracksList[i];

          if (tracks && tracks.length > 0) {
            for (let j = 0; j < tracks.length; j++) {
              let track = tracks[j]
              if (typeof track.stop === 'function') {
                track.stop();
              }

            }
          }
        }
      }
      this.stopInterval();
      this.video = "no-display"
      this.socket.close();
    },
    initWebSocket() {
      if ("WebSocket" in window) {
        if (this.socket == null) {
          this.socket = new WebSocket(this.websocketUrl + "/" + this.examId + "/" + this.$store.state.user.userId, [getToken()])
        }

        this.socket.onopen = this.onOpen;
        this.socket.onclose = this.onClose;
        this.socket.onerror = this.onError;
        this.socket.onmessage = this.onMessage;
        // this.start();
      }

    },
    onOpen() {
      console.log("webSocket connect successfully")
      this.start();
    },
    onClose(err) {
      console.log("webSocket closed")
      console.log(err)
      this.stopVideo()
    },
    onMessage(event) {
      // console.log(JSON.parse(event.data))
    },
    onError(e) {
      console.log("webSocket error: " + e)
      // this.stopInterval();
      this.stopVideo()
    },

    start() {
      this.interval = setInterval(() => {
        if (this.socket != null) {
          this.$refs.canvas.getContext('2d').drawImage(this.$refs.video, 0, 0 , 300 ,150)
          this.socket.send(this.$refs.canvas.toDataURL('image/jpeg', 0.4))
          
        }
      }, 50)
    },
    stopInterval() {
      if (this.interval != null) {
        clearInterval(this.interval)
      }
    },
    beforeunloadHandler() {
      this._beforeUnload_time = new Date().getTime();
    },
    unloadHandler(e) {
      this._gap_time = new Date().getTime() - this._beforeUnload_time;
      //判断是窗口关闭还是刷新
      if (this._gap_time <= 5) {
        if (this.socket != null) {
          this.socket.close();
        }
      }
    }

  }
}
</script>
<style scoped>
.video {

  position: fixed;
  display: flex;
  flex-direction: row;

}

.no-display {
  width: 250px;

  height: 250px;
  display: none;
  

}

.close-video {
  cursor: pointer;
  width: 40px;
  height: 40px;
  z-index: 999;
  transform: translate(260px, 40px);
  color: white;
  text-align: center;
}

#video {
  width: 250px;

  height: 250px;
}
</style>